from django.template import Context, loader
from bouting.models import *
from django.http import HttpResponse
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import HttpResponseRedirect
from django.core.mail import send_mail
from django.utils import simplejson
from django.core import serializers
import datetime
import re


def notYours(request):
    return HttpResponse("Hey! That's not yours to mess with!")

def signUp(request):
    if request.method == "POST":        

        newUser = User()
        userForm = UserForm(request.POST, instance=newUser)
        person = Person(createdBy=newUser, editedBy=newUser)
        personForm = PersonForm(request.POST, instance=person)
        card = UsfaCard(createdBy=newUser, editedBy=newUser, person=person)
        usfaCardForm = UsfaCardForm(request.POST, instance=card)
        if personForm.is_valid() and usfaCardForm.is_valid() and userForm.is_valid():
            newU = userForm.save(commit=False)
            newU.set_password(userForm.cleaned_data['password'])
            newU.save()
            newPerson = personForm.save(commit=False)
            newPerson.createdBy=newUser
            newPerson.editedBy=newUser
            newPerson.save()
            newForm = usfaCardForm.save(commit=False)
            newForm.person = person
            newForm.createdBy=newUser
            newForm.editedBy=newUser
            newForm.save()
            return HttpResponseRedirect('/bouting/')
        else:
            usfaCardForm = UsfaCardForm(request.POST)
    else:
        personForm = PersonForm()
        usfaCardForm = UsfaCardForm()
        userForm = UserForm()
    
    return render_to_response('bouting/signUp.html', {'personForm' : personForm,
                                                      'usfaCardForm' : usfaCardForm,
                                                      'userForm' : userForm,
                                                      }, context_instance=RequestContext(request) )

def signOut(request):
    logout(request)
    return render_to_response('bouting/signOut.html', {}, context_instance=RequestContext(request) )

def signIn(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            return HttpResponse("Hello, world. You're at the poll index.")
    else:
        return HttpResponse("Hello, world. You're at the poll index.")
        
    return render_to_response('bouting/signIn.html', {}, context_instance=RequestContext(request) )

def index(request):
    #t = loader.get_template('bouting/index.html')
    #c = Context({})
    #return HttpResponse(t.render(c))
    return render_to_response('bouting/index.html', {}, context_instance=RequestContext(request) )
    
@login_required(redirect_field_name='/bouting/')
def myTournamentList(request):
    tournamentList = Tournament.objects.all().filter(owners=request.user)
    return render_to_response('bouting/tournamentList.html', {'tournamentList' : tournamentList}, context_instance=RequestContext(request) )
    
def tournamentList(request):
    tournamentList = Tournament.objects.all()
    return render_to_response('bouting/tournamentList.html', {'tournamentList' : tournamentList}, context_instance=RequestContext(request) )

@login_required(redirect_field_name='/bouting/')
def personList(request):
    latest_person_list = Person.objects.all().order_by('firstName')
    #t = loader.get_template('bouting/personList.html')
    #c = Context({
    #    'latest_person_list': latest_person_list,
    #})
    #return HttpResponse(t.render(c))
    return render_to_response('bouting/personList.html', {'latest_person_list' : latest_person_list}, context_instance=RequestContext(request) )
  
def createClub(request):
    if request.method == 'POST':
        club = Club(createdBy=request.user, editedBy=request.user)
        form = ClubForm(request.POST, instance=club)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/bouting/') # Redirect after POST
    else:
        form = ClubForm() # An unbound form

    return render_to_response('bouting/createClub.html', {
        'form': form,
    }, context_instance=RequestContext(request))

def editClub(request, club_id):
    try:
        club = Club.objects.get(id=club_id)
    except:
        raise Http404
    
    if not request.user in club.owners.all():
        return notYours(request)
    
    if request.method == 'POST':
        form = ClubForm(request.POST, instance=club)
        if form.is_valid():
            form.editedBy = request.user
            # Update the owners of all tournaments to include potentially new club owners
            form.save()
            tournamentList = Tournament.objects.all().filter(hostClub=club)
            for tournament in tournamentList:
                tournament.owners = club.owners.all()
                tournament.save()
            return HttpResponseRedirect('/bouting/clubList/') # Redirect after POST
    else:
        form = ClubForm(instance = club)

    return render_to_response('bouting/editClub.html', {
        'form': form,
        'club' : club,
    }, context_instance=RequestContext(request))

def clubDetail(request, club_id):
    try:
        club = Club.objects.get(id=club_id)
    except:
        raise Http404
    return render_to_response('bouting/clubDetail.html', {'club' : club}, context_instance=RequestContext(request) )

def clubList(request):
    clubList = Club.objects.all()
    return render_to_response('bouting/clubList.html', {'clubList' : clubList}, context_instance=RequestContext(request) )
    
def myClubList(request):
    clubList = Club.objects.all().filter(owners=request.user)
    return render_to_response('bouting/clubList.html', {'clubList' : clubList}, context_instance=RequestContext(request) )

def deleteClub(request, club_id):
    try:
        club = Club.objects.get(pk=club_id)
    except Club.DoesNotExist:
        raise Http404
    
    if not request.user in club.owners.all():
        return notYours(request)
    
    Club.objects.all().filter(pk=club_id).delete()
    return HttpResponseRedirect('/bouting/clubList/')

def editPerson(request, person_id, tournament_id="", event_id=""):
    try:
        person = Person.objects.all().get(pk=person_id)
        card = UsfaCard.objects.all().get(person=person)
    except:
        raise Http404
    
    print "t:" + tournament_id
    if tournament_id == "" and event_id == "":
        redirect = '/bouting/'
    else:
        try:
            tournament = Tournament.objects.get(pk=tournament_id)
            event = Event.objects.get(pk=event_id)
            redirect='/bouting/'+tournament_id+"/"+event_id+"/confirmEntrants/"
        except Exception:
            raise Http404
    
    if request.method == 'POST':
        formA = PersonForm(request.POST, instance=person)
        formB = UsfaCardForm(request.POST, instance=card)
        if formA.is_valid() and formB.is_valid():
            formA.editedBy = request.user
            formA.save()
            formB.person = person
            formB.save()
            return HttpResponseRedirect(redirect)
        else:
            formB = UsfaCardForm(request.POST, instance=card)
    else:
        formA = PersonForm(instance=person)
        formB = UsfaCardForm(instance=card)

    return render_to_response('bouting/editPerson.html', {
        'formA': formA,
        'formB': formB,
        'person': person,
        'tournament' : tournament,
        'event' : event,
    }, context_instance=RequestContext(request))
    
def createPerson(request):
    if request.method == 'POST':
        person = Person(createdBy=request.user, editedBy=request.user)
        formA = PersonForm(request.POST, instance=person)
        card = UsfaCard(createdBy=request.user, editedBy=request.user, person=person)
        formB = UsfaCardForm(request.POST, instance=card)
        if formA.is_valid() and formB.is_valid():
            formA.save()
            newForm = formB.save(commit=False)
            newForm.person = person
            newForm.save()
            return HttpResponseRedirect('/bouting/')
        else:
            formB = UsfaCardForm(request.POST)
    else:
        formA = PersonForm()
        formB = UsfaCardForm()

    return render_to_response('bouting/createPerson2.html', {
        'formA': formA,
        'formB': formB,
    }, context_instance=RequestContext(request))

def deleteEntrant(request, tournament_id, event_id, entrant_id):
    try:
        event = Event.objects.get(pk=event_id)
        entrant = Entrant.objects.get(pk=entrant_id)
        tournament = Tournament.objects.get(pk=tournament_id)
    except Exception as e:
        raise Http404
    
    #if not request.user in t.owners.all():
    #    return notYours(request)
        
    events = Event.objects.all().filter(tournament=tournament_id)
    personList = Person.objects.all()
    
    Entrant.objects.all().filter(pk=entrant_id).delete()
    return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentDetail/') # Redirect after POST
    
def createEntrant(request, tournament_id, event_id):
    try:
        event = Event.objects.get(pk=event_id)
        tournament = Tournament.objects.get(pk=tournament_id)
    except Exception as e:
        print e
        raise Http404
    
    #if not request.user in tournament.owners.all():
    #    return notYours(request)
        
    if request.method == 'POST':
        entrant = Entrant(createdBy=request.user, editedBy=request.user, event=event)
        form = EntrantForm(request.POST, instance=entrant)
        if form.is_valid():
            # If the entrant is not allowed to enter the tournament
            if not form.cleaned_data['identity'] in event.getPossibleEntrants():
                return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentView/')
            form.save()
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentView/') # Redirect after POST
    else:
        pass
    return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentDetail/') # Redirect after POST

def deleteRef(request, tournament_id, event_id, referee_id):
    try:
        event = Event.objects.get(pk=event_id)
        referee = Referee.objects.get(pk=referee_id)
        t = Tournament.objects.get(pk=tournament_id)
    except Exception as e:
        raise Http404
    
    if not request.user in t.owners.all():
        return notYours(request)
        
    events = Event.objects.all().filter(tournament=tournament_id)
    personList = Person.objects.all()
    
    # Check permissions
    if request.user.has_perm('bouting.delete_referee'):
        Referee.objects.all().filter(pk=referee_id).delete()
        return render_to_response('bouting/createRef_Success.html', {'tournament': t, 'eventList' : events, 'personList' : personList}, context_instance=RequestContext(request))
    else:
        return notYours(request)
    
def createRef(request, tournament_id, event_id):
    try:
        event = Event.objects.get(pk=event_id)
        tournament = Tournament.objects.get(pk=tournament_id)
    except Exception as e:
        print e
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
    if request.method == 'POST':
        ref = Referee(createdBy=request.user, editedBy=request.user, event=event)
        form = RefereeForm(request.POST, instance=ref)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentDetail/') # Redirect after POST
    else:
        pass
    return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentDetail/') # Redirect after POST

def tournamentView(request, tournament_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        activeEventList = Event.objects.all().filter(tournament=tournament)
    except Exception:
        raise Http404
    
    #if not request.user in tournament.owners.all():
        #return notYours(request)
        
    return render_to_response('bouting/tournamentView.html', {
        'tournament' : tournament,
        'eventList' : activeEventList,
    }, context_instance=RequestContext(request))
    
def roundView(request, tournament_id, event_id, roundNum):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(event=event,roundNum=roundNum)
    except Exception:
        raise Http404
    
    #if not request.user in tournament.owners.all():
     #   return notYours(request)
    
    # if the current round is a pool round, show the pool view
    return render_to_response('bouting/roundView.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
    }, context_instance=RequestContext(request))

def eventView(request, tournament_id, event_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = event.getCurrentRound()
        roundList = Round.objects.all().filter(event=event)
    except Exception:
        raise Http404
    
    #if not request.user in tournament.owners.all():
     #   return notYours(request)
    
    # if the current round is a pool round, show the pool view
    return render_to_response('bouting/eventView.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
        'roundList' : roundList,
    }, context_instance=RequestContext(request))
    
    #('/bouting/' +str(tournament.id)+ '/' +str(event.id) + '/eventView/')
    
def roundResults(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
    except Exception:
        raise Http404
    
    fencerList = Fencer.objects.all().filter(round__event=event, round=round).order_by('place')

    
    # For DE's, compute the finished fencer's positions
    if round.type == 2:
        round.determineDePlacement()
    else:
        fencerList = Fencer.objects.all().filter(round__event=event, round=round).order_by('place')
        
    return render_to_response('bouting/roundResults.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
        'fencerList' : fencerList
    }, context_instance=RequestContext(request))

def editBout(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
    except Exception:
        raise Http404
    if not request.user in tournament.owners.all():
        return notYours(request)
        
    # Get the bout and the necessary data, then save it
    if request.method=="POST":
        bout = Bout.objects.get(pk=request.POST["bout"])
        bout.leftScore = int(request.POST[str(tournament.id)+"-"+str(event.id)+"-"+str(round.roundNum)+"-"+"leftScore"])
        bout.rightScore = int(request.POST[str(tournament.id)+"-"+str(event.id)+"-"+str(round.roundNum)+"-"+"rightScore"])
        bout.finished = request.POST["done"]
        bout.save()
        
        if bout.nextBout != None:
            nextBout = bout.nextBout
            if nextBout != None:
                if bout.getWinner() == bout.leftFencer:
                    nextBout.leftFencer = bout.leftFencer
                elif bout.getWinner() == bout.rightFencer:
                    nextBout.rightFencer = bout.rightFencer
                nextBout.save()
    
    print "wooo we done!"
    # Get all the bouts...    
    boutList = Bout.objects.all().filter(cluster__round__event=event)
    
    print "bouts to go: " + str(boutList)
    
    # TODO: There is a better way to do this by checking if the boutList is empty and returning only unfinished bouts
    # And see if they are all done...
    done = True
    for bout in boutList:
        if not bout.finished:
            done = False
            print "NOT DONE: " + str(bout)
            break
    
    # If they are, set the status of the event...
    if done and round.type == 1:
        event.status = 4
        round.isFinished = True
        round.save()
        event.save()
        
        # And then set each fencer's rank for each cluster...
        for cluster in Cluster.objects.all().filter(round=round):
            
            # TODO: Eventually will have to go back and account for ties.
            fencerList = Fencer.objects.all().filter(cluster=cluster)
            fencerList = sorted(fencerList, cmp=lambda x,y: cmp(y.getTR(), x.getTR()))
            fencerList = sorted(fencerList, cmp=lambda x,y: cmp(y.getTS(), x.getTS()))
            fencerList = sorted(fencerList, cmp=lambda x,y: cmp(y.getD(), x.getD()))
            fencerList = sorted(fencerList, cmp=lambda x,y: cmp(y.getV(), x.getV()))
            fencerList = sorted(fencerList, cmp=lambda x,y: cmp(y.getInd(), x.getInd()))
            fencerList = sorted(fencerList, cmp=lambda x,y: cmp(y.getVP(), x.getVP()))
            
            i = 1
            for fencer in fencerList:
                fencer.place = i
                i = i + 1
                fencer.save()
        event.generateInitialSeeding(request.user)
    
    if done and round.type == 2:
        event.status = 4
        round.isFinished = True
        round.save()
        event.save()
    
    return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentView/')
    #return HttpResponseRedirect('/bouting/'+str(tournament.id) +'/' + str(event.id) +'/' + str(round.id) +'/poolView/')
def poolView(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
        clusterList = Cluster.objects.all().filter(round=round_id)
    except Exception:
        raise Http404
    
    if not request.user in tournament.owners.all() or round.isFinished:
        canEdit = False
    else:
        canEdit = True
        
    if request.is_ajax():
        data = render_to_response('bouting/poolView.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
        'poolList' : clusterList,
        'canEdit' : canEdit,
    }, context_instance=RequestContext(request))
        return HttpResponse(data)
        
    return render_to_response('bouting/poolView.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
        'poolList' : clusterList,
        'canEdit' : canEdit,
    }, context_instance=RequestContext(request))
    
def prepareBouts(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
        clusterList = Cluster.objects.all().filter(round=round_id)
    except Exception:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
    
    # TODO: THIS IS BAAAAAAAD
    #Bout.objects.all().filter(round=round).delete()

    # If preparing for pools...
    if round.type == 1:
        for pool in clusterList:
            # Clean out old bouts that might exist
            i = 0
            fencersInPool = Fencer.objects.all().filter(cluster=pool)
            for fencerA in fencersInPool:
                fencerA.number = i+1
                fencerA.save()
                for fencerB in fencersInPool[i:]:
                    if fencerA != fencerB:
                        bout = Bout(leftFencer=fencerB,
                                    rightFencer=fencerA,
                                    cluster=pool,
                                    createdBy=request.user,
                                    editedBy=request.user)
                        bout.save()
                i = i + 1
                        
        boutList = Bout.objects.all()
    
    return HttpResponseRedirect('/bouting/'+str(tournament.id) + '/tournamentView/')

def beginFencing(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
    except Exception:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
    
    event.status = 3
    event.save()
    return render_to_response('bouting/beginFencing.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
    }, context_instance=RequestContext(request))

def prePool(request, tournament_id, event_id, roundNum):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(event=event,roundNum=roundNum)
        clusterList = Cluster.objects.all().filter(round=round.id)
    except Exception:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
    
    poolList = []
    for pool in clusterList:
        poolList.append(Fencer.objects.all().filter(cluster=pool))
        
    fencerList = Fencer.objects.all().filter(round__event=event, round=round)
    
    # If the initial seeding hasn't been created yet, make it
    if str(fencerList) == "[]":
        entrantList = event.generateInitialSeeding(request.user)
        fencerList = Fencer.objects.all().filter(round__event=event)
        event.status = 1
        event.editedBy = request.user
        event.save()
    
    options = round.generatePoolOptions()
    
    return render_to_response('bouting/prePool.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
        'poolList' : poolList,
        
    }, context_instance=RequestContext(request))
    
def deView(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
        clusterList = Cluster.objects.all().filter(round=round_id)
    except Exception:
        raise Http404
    
    # TODO: Need to go back and change the canedit variable to include other times you can't edit (like the pool is finished)
    if not request.user in tournament.owners.all():
        canEdit = False
    else:
        canEdit = True
    
    #if len(clusterList) == 0:
    #    round.generateDeTable(request.user)
    
    round.generateDeTable(request.user)
    #if len(clusterList) == 0:
    #    round.generateDeTable(request.user)
    #else:
    #    print "We got clusters!"
    
    try:
        firstCluster = clusterList.get(number=1)
        print "woo2"
    except Exception as e:
        print e
    
    print event
    print tournament
    print round
    print clusterList
    print firstCluster
    print canEdit
    return render_to_response('bouting/deView.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
        'clusterList' : clusterList,
        'firstCluster' : firstCluster,
        'canEdit' : canEdit,
    }, context_instance=RequestContext(request))    
    
def generatePools(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
        clusterList = Cluster.objects.all().filter(round=round_id)
    except Exception:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
    
    poolList = []
    for pool in clusterList:
        poolList.append(Fencer.objects.all().filter(cluster=pool))

    return render_to_response('bouting/generatePools.html', {
        'event' : event,
        'tournament' : tournament,
        'round' : round,
        'poolList' : poolList,
        
    }, context_instance=RequestContext(request))    
    
def poolOptions(request, tournament_id, event_id, roundNum):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(event=event,roundNum=roundNum)
    except Exception:
        raise Http404

    if not request.user in tournament.owners.all():
        return notYours(request)
        
    if request.method == 'POST':
        format = request.POST['format']
        
        try:
            primary = request.POST['primary']
        except:
            primary = False
        try:
            secondary = request.POST['secondary']
        except:
            secondary = False
        try:
            name = request.POST['name']
        except:
            name = False
        try:
            division = request.POST['division']
        except:
            division = False
            
        # Protect against sending strange answers, basically serves as "is_valid"
        options = round.generatePoolOptions()
        if format in options:
            m = re.split(" ", format)
            totalPools = int(m[0])
            totalBigPools = int(m[2])
            bigPoolSize = int(m[5])
            
            # If there are no small pools, this would normally cause an error
            try:
                totalSmallPools = int(m[7])
            except:
                totalSmallPools = 0
            
            round.generatePools(totalPools, totalBigPools, bigPoolSize, totalSmallPools, request.user, primary, secondary, name, division)
            event.status = 2
            event.editedBy = request.user
            event.save()
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentView/') # Redirect after POST
        else:
            raise Http404
        
    options = round.generatePoolOptions()
    
    return render_to_response('bouting/poolOptions.html', {
        'event' : event,
        'tournament' : tournament,
        'optionList' : options,
        'round' : round,
        
    }, context_instance=RequestContext(request))  
   
def initialSeeding(request, tournament_id, event_id, round_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        round = Round.objects.get(pk=round_id)
    except Exception:
        raise Http404
    
    if event.getCurrentRound() == round:
        isCurrent = True
    else:
        isCurrent = False

    if request.method == 'POST':
        entrantList = event.generateInitialSeeding(request.user)
        event.status = 1
        event.editedBy = request.user
        event.save()
        return HttpResponseRedirect('/bouting/'+str(tournament.id) +'/' + str(event.id) +'/' + str(round.id) +'/prePool/')
    fencerList = Fencer.objects.all().filter(round__event=event, round=round)

    return render_to_response('bouting/initialSeeding.html', {
        'event' : event,
        'tournament' : tournament,
        'fencerList' : fencerList,
        'round' : round,
        'isCurrent' : isCurrent,
        
    }, context_instance=RequestContext(request))  
    
def confirmEntrants(request, tournament_id, event_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
    except Exception:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
        
    #rounds = Round.objects.all().filter(event=event)
    #
    #rounds[0].generatePoolOptions()
    entrantList = event.getEntrants()
        
    return render_to_response('bouting/confirmEntrants.html', {
        'event' : event,
        'tournament' : tournament,
        'entrantList' : entrantList,
        
    }, context_instance=RequestContext(request))
    
def createEvent(request, tournament_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
    except Tournament.DoesNotExist:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
        
    if request.method == 'POST':
        event = Event(createdBy=request.user, editedBy=request.user, tournament=tournament)
        eventForm = EventForm(request.POST, instance=event)
        
        roundForms = [RoundForm(request.POST, prefix=str(x)) for x in range(0,2)]
        
        # If the values from the forms are good, update the round so that the event is set
        if eventForm.is_valid() and all([roundForm.is_valid() for roundForm in roundForms]):
            eventForm.save()
            c = 1
            for roundForm in roundForms:
                newRound = roundForm.save(commit=False)
                newRound.event = event
                newRound.roundNum = c
                c = c + 1
                newRound.createdBy = request.user
                newRound.editedBy = request.user
                newRound.save()
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentView/') # Redirect after POST
    else:
        roundForms = [RoundForm(prefix=str(x)) for x in range(0,2)]
        eventForm = EventForm()

    return render_to_response('bouting/createEvent.html', {
        'eventForm': eventForm,
        'roundForms': roundForms,
        'tournament' : tournament,
    }, context_instance=RequestContext(request))

def deleteEvent(request, tournament_id, event_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        e = Event.objects.get(pk=event_id)
    except Tournament.DoesNotExist, Event.DoesNotExist:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
    
    if request.user.has_perm('bouting.delete_event'):
        Event.objects.all().filter(pk=event_id).delete()
        return render_to_response('bouting/deleteEvent_Success.html', {'tournament' : tournament}, context_instance=RequestContext(request))

def advanceRounds(request, tournament_id, event_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        rounds = Round.objects.all().filter(event=event)
    except Tournament.DoesNotExist:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
        
    if request.method == 'POST':
        eventForm = EventForm(request.POST, instance=event)
        
        roundForms = [RoundForm(request.POST, prefix=str(x), instance=rounds[x]) for x in range(0,2)]
        
        # If the values from the forms are good, update the round so that the event is set
        if eventForm.is_valid() and all([roundForm.is_valid() for roundForm in roundForms]):
            eventForm.editedBy = request.user
            eventForm.save()
            for roundForm in roundForms:
                roundForm.editedBy = request.user
                roundForm.save()
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentDetail/') # Redirect after POST
    else:
        roundForms = [RoundForm(prefix=str(x), instance=rounds[x]) for x in range(0,2)]
        eventForm = EventForm(instance=event)

    return render_to_response('bouting/editEvent.html', {
        'eventForm': eventForm,
        'roundForms': roundForms,
        'tournament' : tournament,
        'event' : event,
    }, context_instance=RequestContext(request))

def editEvent(request, tournament_id, event_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
        event = Event.objects.get(pk=event_id)
        rounds = Round.objects.all().filter(event=event)
    except Tournament.DoesNotExist:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
        
    if request.method == 'POST':
        eventForm = EventForm(request.POST, instance=event)
        
        roundForms = [RoundForm(request.POST, prefix=str(x), instance=rounds[x]) for x in range(0,2)]
        
        # If the values from the forms are good, update the round so that the event is set
        if eventForm.is_valid() and all([roundForm.is_valid() for roundForm in roundForms]):
            eventForm.editedBy = request.user
            eventForm.save()
            for roundForm in roundForms:
                roundForm.editedBy = request.user
                roundForm.save()
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentDetail/') # Redirect after POST
    else:
        roundForms = [RoundForm(prefix=str(x), instance=rounds[x]) for x in range(0,2)]
        eventForm = EventForm(instance=event)

    return render_to_response('bouting/editEvent.html', {
        'eventForm': eventForm,
        'roundForms': roundForms,
        'tournament' : tournament,
        'event' : event,
    }, context_instance=RequestContext(request))

def createTournament(request):
    if request.method == 'POST':
        tournament = Tournament(createdBy=request.user, editedBy=request.user)
        form = TournamentForm(request.POST, instance=tournament)
        if form.is_valid():
            form.save()
            
            # Set the tournament creator and all owners of the host club as owners
            tournament.owners.add(request.user)
            for clubOwner in tournament.hostClub.owners.all():
                tournament.owners.add(clubOwner)
                
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentView/') # Redirect after POST
    else:
        form = TournamentForm() # An unbound form

    return render_to_response('bouting/createTournament.html', {
        'form': form,
    }, context_instance=RequestContext(request))
    
def editTournament(request, tournament_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
    except Tournament.DoesNotExist:
        raise Http404
    if not request.user in tournament.owners.all():
        return notYours(request)
        
    if request.method == 'POST':
        form = TournamentForm(request.POST, instance = tournament)
        if form.is_valid():
            form.editedBy = request.user
            form.save()
            return HttpResponseRedirect('/bouting/'+str(tournament.id)+'/tournamentDetail/')
    else:
        form = TournamentForm(instance=tournament)
    return render_to_response('bouting/editTournament.html', {
        'form': form,
        'tournament' : tournament,
    }, context_instance=RequestContext(request))
    
def deleteTournament(request, tournament_id):
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
    except Tournament.DoesNotExist:
        raise Http404
    
    if not request.user in tournament.owners.all():
        return notYours(request)
    
    # Check permissions
    if request.user.has_perm('bouting.delete_tournament'):
        Tournament.objects.all().filter(pk=tournament_id).delete()
        return render_to_response('bouting/deleteTournament_Success.html', {}, context_instance=RequestContext(request) )

def tournamentDetail(request, tournament_id):
    try:
        t = Tournament.objects.get(pk=tournament_id)
    except Tournament.DoesNotExist:
        raise Http404
    
    #if not request.user in t.owners.all():
    #    return notYours(request)
    
    events = Event.objects.all().filter(tournament=tournament_id)
    entrantForm = EntrantForm()
    refForm = RefereeForm(auto_id='ref-%s')
    try:
        person = Person.objects.all().get(account=request.user)
    except:
        person = ""
        
        
    return render_to_response('bouting/tournamentDetail.html', {'tournament': t,
                                                                'eventList' : events,
                                                                'entrantForm' : entrantForm,
                                                                'refForm' : refForm,
                                                                'person' : person}, context_instance=RequestContext(request))
    
def detail(request, person_id):
    try:
        p = Person.objects.get(pk=person_id)
        try:
            c = UsfaCard.objects.get(person=p)
        except:
            c = "N/A"
    except Person.DoesNotExist:
        raise Http404
    return render_to_response('bouting/detail.html', {'person': p, 'card' : c}, context_instance=RequestContext(request))
